/*
 * Copyright (c) 2013-2014, starteasy Inc. All Rights Reserved.
 * 
 * Project Name: sample
 * $Id:  2016-11-14 17:11:28 $ 
 */
package cn.starteasy.sample.web.controller.api;

import cn.starteasy.core.common.domain.persistent.SearchEnum;
import cn.starteasy.core.common.domain.persistent.utils.ConditionBuilder;
import cn.starteasy.core.common.domain.wrapper.BooleanWrapper;
import cn.starteasy.sample.service.ICountryService;
import cn.starteasy.core.common.domain.view.admin.SearchField;
import cn.starteasy.core.common.domain.wrapper.StringWrapper;
import cn.starteasy.core.common.domain.view.BizData4Page;
import cn.starteasy.core.common.exception.BizException;
import cn.starteasy.core.common.protocol.utils.RtnCodeEnum;

import cn.starteasy.sample.domain.Country;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value="/api")
public class ApiCountryController{
    private static final Logger logger = LoggerFactory.getLogger(ApiCountryController.class);

    @Autowired
    private ICountryService countryService;

   /**
     * 新增 国家
     * @param country
     * @return  处理条数
     */
    @ResponseBody
    @RequestMapping(value = "/country", method = RequestMethod.POST)
    public Object addCountry(@RequestBody Country country) {
        try {
            String msg = "";

            if(country==null) {
                msg = "添加国家参数不正确";
            }else if(country.getStatus() != null){
                msg = "国家状态不能为空";
            }else if(country.getCreator() != null){
                msg = "国家创建人不能为空";
            }else if(country.getCreateDate() != null){
                msg = "国家创建时间不能为空";
            }else if(country.getLastModifier() != null){
                msg = "国家修改人不能为空";
            }else if(country.getLastModDate() != null){
                msg = "国家修改时间不能为空";
            }

            if(StringUtils.isNotBlank(msg)){
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), msg);
            }

            countryService.create(country);
            return new BooleanWrapper(true);
        } catch (BizException bize) {
            throw bize;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "新增国家异常");
        }
    }


    /**
     * 删除 国家
     *
     * @param {countryId} 国家ID
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/country/{countryId}" ,method = RequestMethod.DELETE)
    public Object delCountry(@PathVariable String countryId) {
        try {
            if(StringUtils.isBlank(countryId)){
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "删除国家失败，参数不正确");
            }
            countryService.deleteByCondition(ConditionBuilder.condition("id", SearchEnum.eq, countryId));
            return new BooleanWrapper(true);
        } catch (BizException bize) {
            throw bize;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "删除国家异常");
        }
    }


    /**
     * 修改国家数据
     * @param country 提交上来的国家JSON数据
     * @param countryId  国家ID
     * @return  修改条数
     */
    @ResponseBody
    @RequestMapping(value = "/country/{countryId}", method = RequestMethod.PATCH)
    public StringWrapper editCountry(@RequestBody Country country, @PathVariable String countryId) {
        try {
            String msg = "";
            if(country==null) {
                msg = "添加国家参数不正确";
            }else if(country.getStatus() != null){
                msg = "国家状态不能为空";
            }else if(country.getCreator() != null){
                msg = "国家创建人不能为空";
            }else if(country.getCreateDate() != null){
                msg = "国家创建时间不能为空";
            }else if(country.getLastModifier() != null){
                msg = "国家修改人不能为空";
            }else if(country.getLastModDate() != null){
                msg = "国家修改时间不能为空";

            }

            if(StringUtils.isNotBlank(msg)){
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), msg);
            }

            Country country_old = (Country) countryService.view(country.getId());
            if(country==null) {
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "修改失败，系统未找到相关数据");
            }

            if(country.getId() != null){
                country_old.setId(country.getId());
            }
            if(!StringUtils.isBlank(country.getName())){
                country_old.setName(country.getName());
            }
            if(!StringUtils.isBlank(country.getNumber())){
                country_old.setNumber(country.getNumber());
            }
            if(!StringUtils.isBlank(country.getEname())){
                country_old.setEname(country.getEname());
            }
            if(country.getStatus() != null){
                country_old.setStatus(country.getStatus());
            }
            if(country.getCreator() != null){
                country_old.setCreator(country.getCreator());
            }
            if(country.getCreateDate() != null){
                country_old.setCreateDate(country.getCreateDate());
            }
            if(country.getLastModifier() != null){
                country_old.setLastModifier(country.getLastModifier());
            }
            if(country.getLastModDate() != null){
                country_old.setLastModDate(country.getLastModDate());
            }


            int row=countryService.edit(country_old);
            if(row > 0) {
                return new StringWrapper("修改国家成功");
            }else{
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "修改国家失败");
            }
        } catch (BizException bize) {
            throw bize;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "修改国家数据异常");
        }
    }


    /**
     * 获取单国家实体
     *
     * @param countryId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/country/{countryId}", method = RequestMethod.GET)
    public Country getCountry(@PathVariable String countryId) {
        try {
            if(StringUtils.isBlank(countryId)){
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "参数不正确！");
            }
            Map<String,Object> whereParams = new HashMap<String, Object>();
            whereParams.put("id", countryId);
            Country country= (Country) countryService.viewOne(null, whereParams, null);
            if(null == country){
                throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "系统未找到国家相关数据！");
            }
            return country;
        } catch (BizException bize) {
            throw bize;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "获取单国家实体异常");
        }
    }


    /**
     * 国家数据输出 带分页
     *
     * @param country 过滤条件
     * @param page      第几页
     * @return 业务数据列表实体，最终转换为json数据输出
     * @throws ServletException
     * @throws IOException
     */
    @ResponseBody
    @RequestMapping(value = "/countrylist", method = RequestMethod.POST)
    public BizData4Page countrylist(Country country, Integer page) {
        try {
            Map<String, Object> whereParams = new HashMap<String, Object>();
            if(country.getId() != null){
                whereParams.put("id", new SearchField("id", "=", country.getId()));
            }
            if(!StringUtils.isBlank(country.getName())){
                whereParams.put("name", new SearchField("name", "like", "%" + country.getName() + "%"));
            }
            if(!StringUtils.isBlank(country.getNumber())){
                whereParams.put("number", new SearchField("number", "like", "%" + country.getNumber() + "%"));
            }
            if(!StringUtils.isBlank(country.getEname())){
                whereParams.put("ename", new SearchField("ename", "like", "%" + country.getEname() + "%"));
            }
            if(country.getStatus() != null){
                whereParams.put("status", new SearchField("status", "=", country.getStatus()));
            }
            if(country.getCreator() != null){
                whereParams.put("creator", new SearchField("creator", "=", country.getCreator()));
            }
            if(country.getCreateDate() != null){
                whereParams.put("createDate", new SearchField("createDate", "=", country.getCreateDate()));
            }
            if(country.getLastModifier() != null){
                whereParams.put("lastModifier", new SearchField("lastModifier", "=", country.getLastModifier()));
            }
            if(country.getLastModDate() != null){
                whereParams.put("lastModDate", new SearchField("lastModDate", "=", country.getLastModDate()));
            }


            //other props filter
            whereParams.put("groupOp", "and");

        return countryService.queryPage(null, whereParams, page, 10, 10, null);
        } catch (BizException bize) {
            throw bize;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new BizException(RtnCodeEnum.UNKNOW.getValue(), "查询国家数据异常");
        }
    }
}
